package com.main.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.main.bean.Task;
import com.main.quartz.QuartzUtil;
import com.main.service.TaskService;

@Controller   //类似Struts的Action  
@RequestMapping("/task") 
public class TaskManager {
	
	@Autowired
	private TaskService taskService;
	
	private Logger log=LoggerFactory.getLogger(this.getClass());
	
	@RequestMapping(value="/getNewTask",method=RequestMethod.GET)
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/task/newTask");
        mv.addObject("taskName", taskService.getAllInitTaskName());
        return mv;
    }
	
	@ResponseBody
	@RequestMapping(value="/getTask",method=RequestMethod.POST)
    public Map<String,Object> getContent(@RequestBody JSONObject json){
		Task task=new Task();
		task.setQuartz_name(json.getString("name"));
		taskService.getTaskByName(task);
		Map<String,Object>result=new HashMap<String,Object>();
		result.put("result", "success");
		result.put("content", task);
		return result;
    }
	
	@ResponseBody
	@RequestMapping(value="/saveTask",method=RequestMethod.POST)
    public Map<String,Object> saveContent(@RequestBody JSONObject json){
		Task task=new Task();
		task.setQuartz_name(json.getString("quartz_name"));
		task.setQuartz_ano_name(json.getString("quartz_ano_name"));
		task.setQuartz_class_path(json.getString("quartz_class_path"));
		task.setQuartz_abs(json.getString("quartz_abs"));
		task.setQuartz_corn(json.getString("quartz_corn"));
		task.setQuartz_id(json.getString("quartz_id"));
	    int update=0;
	    if("*".equals(task.getQuartz_id())){
	    	update=taskService.addTask(task);
	    }else{
	    	update=taskService.updateTask(task);
	    }
		Map<String,Object>result=new HashMap<String,Object>();
		result.put("result", update>0?"success":"error");
		result.put("message",update<=0?"更新出错！":"");
		return result;
    }
	

	@ResponseBody
	@RequestMapping(value="/pause",method=RequestMethod.POST)
    public Map<String,Object> pause(@RequestBody JSONObject json){
		Task task=new Task();
		task.setQuartz_id(json.getString("quartz_id"));
	    int update=taskService.updateTaskPauseExcute(task);
	    try {
			QuartzUtil.getQuartzUtil().pauseJob(taskService.getTaskByNameOrByCornNameOrId(task));
		} catch (SchedulerException e) {
			log.error("暂停定时任务出错",e);
		}
		Map<String,Object>result=new HashMap<String,Object>();
		result.put("result", update>0?"success":"error");
		result.put("message",update<=0?"更新出错！":"");
		return result;
    }
	

	@ResponseBody
	@RequestMapping(value="/trig",method=RequestMethod.POST)
    public Map<String,Object> trig(@RequestBody JSONObject json){
		Task task=new Task();
		task.setQuartz_id(json.getString("quartz_id"));
	    int update=1;
	    try {
			QuartzUtil.getQuartzUtil().trigJob(taskService.getTaskByNameOrByCornNameOrId(task));
		} catch (SchedulerException e) {
			log.error("触发定时任务出错",e);
		}
		Map<String,Object>result=new HashMap<String,Object>();
		result.put("result", update>0?"success":"error");
		result.put("message",update<=0?"更新出错！":"");
		return result;
    }
	
	@ResponseBody
	@RequestMapping(value="/addExcute",method=RequestMethod.POST)
    public Map<String,Object> addExcute(@RequestBody JSONObject json){
		Task task=new Task();
		task.setQuartz_id(json.getString("quartz_id"));
	    int update=taskService.updateTaskaddExcute(task);
	    try {
			QuartzUtil.getQuartzUtil().addJob(taskService.getTaskByNameOrByCornNameOrId(task));
		} catch (SchedulerException e) {
			log.error("执行定时任务出错",e);
		}
		Map<String,Object>result=new HashMap<String,Object>();
		result.put("result", update>0?"success":"error");
		result.put("message",update<=0?"更新出错！":"");
		return result;
    }
	
	@ResponseBody
	@RequestMapping(value="/del",method=RequestMethod.POST)
    public Map<String,Object>delExcute(@RequestBody JSONObject json){
		Task task=new Task();
		task.setQuartz_id(json.getString("quartz_id"));
	    int update=taskService.delTaskaddExcute(task);
		try {
			QuartzUtil.getQuartzUtil().removeJob(taskService.getTaskByNameOrByCornNameOrId(task));
		} catch (SchedulerException e) {
			log.error("删除定时任务出错",e);
		}
		Map<String,Object>result=new HashMap<String,Object>();
		result.put("result", update>0?"success":"error");
		result.put("message",update<=0?"更新出错！":"");
		return result;
    }
	
	@RequestMapping(value="/manager",method=RequestMethod.GET)
    public ModelAndView manager(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/task/taskManager");
        return mv;
    }
	
	@ResponseBody
	@RequestMapping(value="/queryList",method=RequestMethod.POST)
    public  Map<String,Object> queryList(HttpServletRequest request){
		 String table = "QUARTZ_TASK";
		 //获取请求次数
	    String draw = "0";
	    draw = request.getParameter("draw");
	    //数据起始位置
	    String start = request.getParameter("start");
	    //数据长度
	    String length = request.getParameter("length");
	    length=String.valueOf(Integer.parseInt(start)+Integer.parseInt(length));
	    start=String.valueOf(Integer.parseInt(start)+1);
	    //总记录数
	    String recordsTotal = "0";
	    //过滤后记录数
	    String recordsFiltered = "";
	    String[] cols = {"","quartz_id", "quartz_name", "quartz_ano_name", "quartz_class_path", "quartz_corn", "quartz_abs"};
	    //获取客户端需要那一列排序
	    String orderColumn = "0";
	    orderColumn = request.getParameter("order[0][column]");
	    orderColumn = cols[Integer.parseInt(orderColumn)];
	    //获取排序方式 默认为asc
	    String orderDir = "asc";
	    orderDir = request.getParameter("order[0][dir]");
	    
	    //获取用户过滤框里的字符
	    String searchValue = request.getParameter("search[value]");
	    
	    List<String> sArray = new ArrayList<String>();
	    if (!searchValue.equals("")) {
	        sArray.add(" quartz_id like '%" + searchValue + "%'");
	        sArray.add(" quartz_name like '%" + searchValue + "%'");
	        sArray.add(" quartz_ano_name like '%" + searchValue + "%'");
	        sArray.add(" quartz_class_path like '%" + searchValue + "%'");
	        sArray.add(" quartz_corn like '%" + searchValue + "%'");
	        sArray.add(" quartz_abs like '%" + searchValue + "%'");
	    }

	    String individualSearch = "";
	    if (sArray.size() == 1) {
	        individualSearch = sArray.get(0);
	    } else if (sArray.size() > 1) {
	        for (int i = 0; i < sArray.size() - 1; i++) {
	            individualSearch += sArray.get(i) + " or ";
	        }
	        individualSearch += sArray.get(sArray.size() - 1);
	    }

	        String recordsFilteredSql = "select count(1) as recordsFiltered from " + table;
	        //获取数据库总记录数
	        String recordsTotalSql = "select count(1) as recordsTotal from " + table;


	        String searchSQL = "";
	        String sql = "SELECT * FROM (SELECT tt.*, ROWNUM AS rowno"+
                                         " FROM (  SELECT t.* from "+ table+ " t";
	        if (individualSearch != "") {
	            searchSQL = " where " + individualSearch;
	        }
	        sql += searchSQL;
	        recordsFilteredSql += searchSQL;
	        sql += " order by " + orderColumn + " " + orderDir+" )tt WHERE ROWNUM <="+length+") ttt WHERE ttt.rowno >="+start;
	        recordsFilteredSql += " order by " + orderColumn + " " + orderDir;
        
	    return taskService.getPage(draw,recordsFilteredSql,recordsTotalSql,sql);
    }
}
